package com.zhoulz.homework.chaptor02.node;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

import com.zhoulz.homework.chaptor02.node.Packet.PacketType;

public class PacketDecode extends ByteToMessageDecoder{
	
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in,
			List<Object> out) throws Exception {
//		System.out.println("decode: "+ in.readableBytes());
		if(in.readableBytes() > 3){
			// 数据包长度
			int length = in.getUnsignedShort(0);
			// 类型
			short type = in.getUnsignedByte(2);
			in.skipBytes(3);
			// 数据
			ByteBuf data = in.readBytes(in.readableBytes());
			
			Packet packet = new Packet(length, PacketType.TYPE.getType(type), data);
			out.add(packet);
		}
	}
}
